﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WHMS.EntityClasses;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;

namespace WMS
{
	public partial class RemoveGeneralItemsRequestForm : Form
	{
		WithdrawRequestEntity _currentRequest;
		DataMngrFormBase<WithdrawRequestItemEntity> _tranItemsForm;
		List<ErrorProvider> _errorProviders;

		public RemoveGeneralItemsRequestForm()
		{
			InitializeComponent();

            WithdrawlDateDTP.Value = DateTime.Now;

		    HideOrViewWeightCol();
		}

	    private void HideOrViewWeightCol()
	    {
            var weightCol = _transItemsGrid.Columns["Weight"];

            if (weightCol != null)
            {
                if (UserInfo.Roles.Where(r => r.ViewWorkshop == true).Count() > 0)
                {
                    weightCol.Visible = true;
                }
                else
                {
                    weightCol.Visible = false;
                }
            }
	    }

	    private void RemoveItemsRequestForm_Load(object sender, EventArgs e)
		{
			_currentRequest = new WithdrawRequestEntity();

			LoadData();

			_errorProviders = new List<ErrorProvider>();

			InitializeDataSources();
		}

		private void InitializeDataSources()
		{
			_currentRequest = new WithdrawRequestEntity();
			_requestItems.RemovedEntitiesTracker = new EntityCollection<WithdrawRequestItemEntity>();

			BindDataSources();

			EnableDisableControls();
		}

		private void BindDataSources()
		{
			_WRequestBS.DataSource = _currentRequest;
		}

		void LoadData()
		{
			DALHelper.FetchCollection(_removeTypes, null, null, new SortExpression(WithdrawalTypeFields.Order | SortOperator.Ascending));

            //FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetRunningGeneralProjects());	
			FormsHelper.LoadComboBox(AccountantsDDL, UserFields.Id, UserFields.Name, (x, y) => Business.GetAccountants(x, y));			

            //FormsHelper.CheckProjects(ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn, bindingNavigator1 }, NoProjectsLbl);
		}

		private void SaveBtn_Click(object sender, EventArgs e)
		{
			if (!ValidateForm())
				return;

			if (!_currentRequest.IsNew)
			{
				if ((bool)DALHelper.GetValue(WithdrawRequestFields.IsApproved, WithdrawRequestFields.Id, _currentRequest.Id))
				{
					RetrieveRequest();
					return;
				}
			}

			_currentRequest.CreatedBy = UserInfo.UserId;
			_currentRequest.Type = "G";
            _currentRequest.ProjectId = GetSelectedProjectId();

			foreach (WithdrawRequestItemEntity item in _requestItems)
			{
				_currentRequest.WithdrawRequestItems.Add(item);
			}

			DALHelper.DeleteCollection(_requestItems.RemovedEntitiesTracker);
			if (DALHelper.SaveEntity(_currentRequest, true))
			{
				RetrieveRequest();
				MessageBox.Show("تم الحفظ بنجاح.");
			}
		}


		
		private bool ValidateForm()
		{
			var isValid = true;

			var controls = new List<Control>();
			controls.Add(WRNumberTB);
            //controls.Add(ProjectsDDL);
			controls.Add(AccountantsDDL);
			controls.Add(TypeDDL);
            controls.Add(ContractorsDDL);
            
			//controls.Add(WithdrawlDateDTP);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var control in controls)
			{
				if (string.IsNullOrEmpty(control.Text.Trim()))
					//(control is TextBox && string.IsNullOrEmpty(control.Text.Trim()))
					//|| (control is ComboBox && control.Text)
					//)
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(control, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}
			}

            if (GetSelectedProjectId() == 0)
            {
                var errorProvider = new ErrorProvider(this);
                _errorProviders.Add(errorProvider);

                errorProvider.SetError(ProjectsTB, "يجب إدخال قيمة صحيحة");
                errorProvider.RightToLeft = true;

                isValid = false;
            }

			if (!ValidateRequestNumber())
				isValid = false;

			if (!_tranItemsForm.IsDataValid())
				isValid = false;

			if (_requestItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}

        //private void ProjectsDDL_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    var projectId = 0;

        //    if (ProjectsDDL.SelectedItem != null)
        //    {
        //        projectId = (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
        //    }

        //    //Business.GetItemsPlannedForProject(projectId, _items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));
        //    //Business.GetItemsPlannedForProject(_items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));

        //    var filter = new RelationPredicateBucket();
        //    filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == projectId)));
        //    FormsHelper.LoadComboBox(ContractorsDDL, ContractorFields.Id, ContractorFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, filter));

        //    ResetTransactionItems();

        //    EnableDisableControls();
        //}
		
		private void ResetTransactionItems()
		   {
			if (_tranItemsForm != null)
			{
				_tranItemsForm.Dispose();
				_tranItemsForm = null;
			}

			var label = new Label();
			_tranItemsForm = new DataMngrFormBase<WithdrawRequestItemEntity>(_requestItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == 0));
			_tranItemsForm.SetNumericFields(new List<int> { 3});
			_tranItemsForm.SetMandatoryFields(new List<int>() { 0, 3});
		}
			
		private int GetSelectedProjectId()
		{
            if (String.IsNullOrEmpty(ProjectsTB.Text))
                return 0;

            int projectid = 0;

            ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text);
            if (project != null)
                return project.Id;

            return projectid;
		}

		private bool ValidateRequestNumber()
		{
			if (!string.IsNullOrEmpty(WRNumberTB.Text.Trim()))
			{
				if (Business.CheckExisitngWithdrawRequestNumber(WRNumberTB.Text.Trim(), _currentRequest.Id))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(WRNumberTB, "رقم الطلب مستخدم");
					errorProvider.RightToLeft = true;
					return false;
				}
				else
				{
					foreach (var errorProvider in _errorProviders)
					{
						if (!string.IsNullOrEmpty(errorProvider.GetError(WRNumberTB)))
						{
							errorProvider.SetError(WRNumberTB, string.Empty);
						}
					}
				}
			}
			return true;
		}

		private void RequestNumberTB_Leave(object sender, EventArgs e)
		{
			ValidateRequestNumber();
		}

		private void RetrieveBtn_Click(object sender, EventArgs e)
		{
			RetrieveRequest();
		}

		private void RetrieveRequest()
		{
			if (string.IsNullOrEmpty(WRNumberTB.Text.Trim()))
				return;

			var collection = new EntityCollection<WithdrawRequestEntity>();

			var filter = new RelationPredicateBucket(WithdrawRequestFields.RequestNumber == WRNumberTB.Text.Trim());
			filter.PredicateExpression.Add(WithdrawRequestFields.Type == "G");

			DALHelper.FetchCollection(collection, filter);

			if (collection.Count <= 0)
			{
				InitializeDataSources();
				return;
			}

			_currentRequest = collection[0];
            var projectfilter = new RelationPredicateBucket(ProjectFields.Id == collection[0].ProjectId);
            EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
            DALHelper.FetchCollection(project, projectfilter);
            ProjectsTB.Text = project[0].Code;
			BindDataSources();

            

			_requestItems.Clear();

			var prefetch = new PrefetchPath2(EntityType.WithdrawRequestItemEntity);
			prefetch.Add(WithdrawRequestItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);
			DALHelper.FetchCollection(_requestItems, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == _currentRequest.Id), prefetch);
           
			ValidateRequestNumber();

			EnableDisableControls();
		}

		void EnableDisableControls()
		{
			_transItemsGrid.Enabled = (!_currentRequest.IsApproved && GetSelectedProjectId() > 0);
			SaveBtn.Enabled = (!_currentRequest.IsApproved && GetSelectedProjectId() > 0);
			bindingNavigator1.Enabled = (!_currentRequest.IsApproved && GetSelectedProjectId() > 0);
			_alreadyApprovedLbl.Visible = _currentRequest.IsApproved;

			ProjectsTB.Enabled = _currentRequest.IsNew;

			NewBtn.Enabled = !_currentRequest.IsNew;
			DeleteBtn.Enabled = !(_currentRequest.IsNew || _currentRequest.IsApproved);
		}

		private void NewBtn_Click(object sender, EventArgs e)
		{
			InitializeDataSources();
            ProjectsTB.Text = string.Empty;
			ResetTransactionItems();
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex == quantityDataGridViewTextBoxColumn.Index)
			{
				var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value;//[itemIdDataGridViewTextBoxColumn.Index].Value;
				if (itemIdValue == null)
					return;

				var form = new UnitConverterForm((int)itemIdValue);
				if (form.ShowDialog() == DialogResult.OK)
				{
					_transItemsGrid.SuspendLayout();
					_transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
					_transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
					_transItemsGrid.ResumeLayout(true);
				}
			}
			else if (e.ColumnIndex == ItemCode.Index)//ItemName.Index)
			{
				var form = new ItemPickerForm(1);
				if (form.ShowDialog() == DialogResult.OK)
				{
					GetItemDetails(e.RowIndex, form.SelectedItemId);
					//var _requestItem = (WithdrawRequestItemEntity)_requestItems[e.RowIndex];
					//_requestItem.ItemNameCodeUnit = form.SelectedItemName;
					//_requestItem.ItemId = form.SelectedItemId;

					_transItemsGrid.BeginEdit(false);

					SendKeys.Send("{LEFT}");
					SendKeys.Send("{LEFT}");
					SendKeys.Send("{LEFT}");
					
					var qty = _transItemsGrid.Rows[e.RowIndex].Cells[quantityDataGridViewTextBoxColumn.Index].Value.ToString();
					var chars = qty.ToCharArray();
					foreach(char c in chars)
					{
						SendKeys.Send(c.ToString());
					}
					SendKeys.Send("{ENTER}");
				}				
			}
		}

		private void SearchBtn_Click(object sender, EventArgs e)
		{
			var filter = new RelationPredicateBucket(WithdrawRequestFields.Type == "G");
			filter.Relations.Add(WithdrawRequestEntity.Relations.ProjectEntityUsingProjectId);

			var searchForm = new SearchForm(WithdrawRequestFields.RequestNumber, WithdrawRequestFields.ProjectId, WithdrawRequestFields.RequestDate, filter, ()=> Business.GetRunningProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				WRNumberTB.Text = searchForm.SelectedNumber;
				RetrieveRequest();
			}
		}

		private void DeleteBtn_Click(object sender, EventArgs e)
		{
			var form = new DeleteConfirmationForm();

			if (form.ShowDialog() == DialogResult.Yes)
			{
				if (DALHelper.DeleteEntity(_currentRequest))
				{
					InitializeDataSources();
					ResetTransactionItems();
				}
			}
		}

		private void _transItemsGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex == ItemCode.Index)
			{
				var code = _transItemsGrid.Rows[e.RowIndex].Cells[ItemCode.Index].Value.ToString();
				GetItemDetails(e.RowIndex, code);
				return;
			}
            else if(e.ColumnIndex == quantityDataGridViewTextBoxColumn.Index)
            {
                var itemCollection = new EntityCollection<ItemEntity>();

                var itemId = ((WithdrawRequestItemEntity)(_requestItems[e.RowIndex])).ItemId;

                var itemFilter = new RelationPredicateBucket(ItemFields.Id == itemId);

                DALHelper.FetchCollection(itemCollection, itemFilter);

                if (itemCollection.Count > 0)
                {
                    ((WithdrawRequestItemEntity)(_requestItems[e.RowIndex])).Item = itemCollection[0];
                }
            }
		}		

		private void _transItemsGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
		{
			foreach (DataGridViewRow row in _transItemsGrid.Rows)
			{
				var item = (WithdrawRequestItemEntity)row.DataBoundItem;
				if (item == null)
					continue;

				GetItemDetails(row.Index, item.ItemId);
			}
		}

		private void GetItemDetails(int rowIndex, int itemId)
		{
			var dt = Business.GetItemDetails(itemId);
			if (dt.Rows.Count <= 0)
				return;

			_transItemsGrid.Rows[rowIndex].Cells[ItemCode.Index].Value = (string)dt.Rows[0][0];
			_transItemsGrid.Rows[rowIndex].Cells[ItemName2.Index].Value = (string)dt.Rows[0][1];
			_transItemsGrid.Rows[rowIndex].Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];
			return;
		}

		private void GetItemDetails(int rowIndex, string itemCode)
		{
			var dt = Business.GetItemDetails(itemCode, 1);
			if (dt.Rows.Count <= 0)
				return;

			_transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = (int)dt.Rows[0][0];
			_transItemsGrid.Rows[rowIndex].Cells[ItemName2.Index].Value = (string)dt.Rows[0][1];
			_transItemsGrid.Rows[rowIndex].Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];
			return;
		}

        private void ProjectsTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ProjectsTB.Text))
            {
                ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text.ToString());

                if (project != null)
                {
                    lblProjectName.Text = project.Name;
                    ProjectsTB.Text = project.Code;
                    EnableDisableControls();
                    Business.GetSupplyOrderItemsPlannedForProject(project.Id, _items);
                    var filter = new RelationPredicateBucket();

                    if (TypeDDL.SelectedValue != null)
                    {
                        if ((int)TypeDDL.SelectedValue == 1)//تشغيل
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 3);//تشغيل
                        }
                        else if ((int)TypeDDL.SelectedValue == 4 || (int)TypeDDL.SelectedValue == 5)//بغرض البيع ,أو بالخصم
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 1);//مقاول
                            filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                        }
                        else if ((int)TypeDDL.SelectedValue == 6)
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 2);//وحدات ومستشفيات
                            filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                        }
                    }
                    else
                        filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                    

                    //Business.GetItemsPlannedForProject(projectId, _items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));
                    //Business.GetItemsPlannedForProject(_items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));

                    
                    FormsHelper.LoadComboBox(ContractorsDDL, ContractorFields.Id, ContractorFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, filter));

                    ResetTransactionItems();

                    EnableDisableControls();
                }
                else
                {
                    lblProjectName.Text = string.Empty;
                }
            }
            else
            {
                lblProjectName.Text = string.Empty;
                ContractorsDDL.DataSource = null;
                //RunBtn.Enabled = false;
            }

        }

        private void SearchProjectBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();
            //var filter = new RelationPredicateBucket(ProjectFields.Id == _currentTransaction.ProjectId); //TODO
            var filter = new RelationPredicateBucket(ProjectFields.Status == "جارى");
            filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);
            var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                            () => Business.GetRunningAndGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                ProjectsTB.Text = searchForm.SelectedNumber;
                EnableDisableControls();
            }
        }

        private void TypeDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ProjectsTB.Text))
            {
                ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text.ToString());

                if (project != null)
                {
                    lblProjectName.Text = project.Name;
                    ProjectsTB.Text = project.Code;
                    EnableDisableControls();
                    Business.GetSupplyOrderItemsPlannedForProject(project.Id, _items);
                    var filter = new RelationPredicateBucket();

                    if (TypeDDL.SelectedValue != null)
                    {
                        if ((int)TypeDDL.SelectedValue == 1)//تشغيل
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 3);//تشغيل
                        }
                        else if ((int)TypeDDL.SelectedValue == 4 || (int)TypeDDL.SelectedValue == 5)//بغرض البيع ,أو بالخصم
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 1);//مقاول
                            filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                        }
                        else if ((int)TypeDDL.SelectedValue == 6)
                        {
                            filter.PredicateExpression.Add(ContractorFields.WithdrawzPartyId == 2);//وحدات ومستشفيات
                            filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                        }
                    }
                    else
                        filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));


                    //Business.GetItemsPlannedForProject(projectId, _items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));
                    //Business.GetItemsPlannedForProject(_items, new RelationPredicateBucket(ItemViewFields.TypeId == 1));


                    FormsHelper.LoadComboBox(ContractorsDDL, ContractorFields.Id, ContractorFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, filter));

                    ResetTransactionItems();

                    EnableDisableControls();
                }
                else
                {
                    lblProjectName.Text = string.Empty;
                }
            }
            else
            {
                lblProjectName.Text = string.Empty;
                ContractorsDDL.DataSource = null;
                //RunBtn.Enabled = false;
            }


        }
	}
}
